package shun.demo;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by chen on 3/4/14.
 */
public class MainAdapter extends ArrayAdapter<ResolveInfo> {

    private LayoutInflater mInflater;
    private PackageManager mPackageManager;

    public MainAdapter(Context context, List<ResolveInfo> objects) {
        super(context, 0, objects);
        mInflater = LayoutInflater.from(context);
        mPackageManager = context.getPackageManager();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = createView(parent);
        }
        bindView(position, convertView);
        return convertView;
    }

    private View createView(ViewGroup parent) {
        View view = mInflater.inflate(R.layout.entry, parent, false);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.mIcon = (ImageView) view.findViewById(R.id.app_icon);
        viewHolder.mTitle =  (TextView) view.findViewById(R.id.app_title);
        view.setTag(viewHolder);
        return view;
    }

    private void bindView(int position, View convertView) {
        ResolveInfo ri = getItem(position);
        ViewHolder viewHolder = (ViewHolder) convertView.getTag();
        viewHolder.mIcon.setImageDrawable(ri.loadIcon(mPackageManager));
        viewHolder.mTitle.setText(ri.loadLabel(mPackageManager));
    }

    private static class ViewHolder {
        ImageView mIcon;
        TextView mTitle;
    }
}
